package com.example.utils;

import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;

import lombok.Data;

/**
 * 简单本地缓存器,适用于小规模的静态数据缓存。
 * 失效策略："惰性删除"，即每次查询时进行失效判断
 * 淘汰策略: 无
 * @Author:li
 */
public class MyCacheUtils {
	//ConcurrentHashMap并发读写
	private static ConcurrentHashMap<String, MyCacheData> cacheArea = new ConcurrentHashMap<>();

	//取缓存
	public static Object get(String key) {
		MyCacheData cacheData = cacheArea.get(key);
		if (cacheData == null) {
			return null;
		}
		if (isDead(cacheData)) {
			//惰性删除
			remove(key);
			return null;
		}
		return cacheData.getValue();
	}

	/**
	 * 数据存入缓存
	 * @param key key
	 * @param value value
	 * @param maxAge 毫秒
	 * @return
	 */
	public static boolean put(String key, Object value, long maxAge) {
		MyCacheData data = new MyCacheData();
		data.setCreateTime(new Date().getTime());
		data.setMaxAge(maxAge);
		data.setKey(key);
		data.setValue(value);
		cacheArea.put(key, data);
		return false;
	}

	//是否过期
	private static boolean isDead(MyCacheData data) {
		if (data == null) {
			return true;
		}
		if (data.getMaxAge() == 0) {
			return false;
		}
		long createTime = data.getCreateTime();
		long deadTime = createTime + data.getMaxAge();
		long nowTime = new Date().getTime();
		if (nowTime > deadTime) {
			return true;
		}
		return false;
	}

	//移除
	public static boolean remove(String key) {
		cacheArea.remove(key);
		return true;
	}

	//缓存数据封装
	@Data
	static class MyCacheData {
		//创建时间：单位毫秒
		private long createTime;
		//缓存时常：单位毫秒, 0-标示永不失效
		private long maxAge;
		//数据key
		private String key;
		//数据value
		private Object value;

	}
}
